//
//  ZBPlatformAppDelegate+Safe.m
//  ZBPlatform
//
//  Created by xzb on 2018/10/16.
//

#import "ZBPlatformAppDelegate+Safe.h"
#import <JRSwizzle.h>

static NSString *const kLaunch_Crash_Count = @"ZB_Launch_Crash_Count"; // 是否正在修复

@implementation ZBPlatformAppDelegate (Safe)

+ (void)load
{
    [self jr_swizzleMethod:@selector(application:willFinishLaunchingWithOptions:) withMethod:@selector(zb_application:willFinishLaunchingWithOptions:) error:nil];
    
    [self jr_swizzleMethod:@selector(application:didFinishLaunchingWithOptions:) withMethod:@selector(zb_application:didFinishLaunchingWithOptions:) error:nil];
}

- (BOOL)zb_application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //1.检查
    NSInteger crash_count = [self safeLaunchingCount];
    
    //2.修复
    if (crash_count >= 3) {
        [self clearRootDir];
        [self clearLaunchCount];
    }
    //3.恢复
    return [self zb_application:application willFinishLaunchingWithOptions:launchOptions];
}

- (BOOL)zb_application:(UIApplication *)application didFinishLaunchingWithOptions:(nullable NSDictionary *)launchOptions
{
    [self setupLaunchCount];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self recoverLaunchCount];
    });
    return [self zb_application:application didFinishLaunchingWithOptions:launchOptions];
}

- (NSInteger)safeLaunchingCount
{
    id obj = [[NSUserDefaults standardUserDefaults] valueForKey:kLaunch_Crash_Count];
    if (obj) {
        return [obj integerValue];
    }
    return 0;
}

- (void)setupSafeCount:(NSInteger)count
{
    [[NSUserDefaults standardUserDefaults] setValue:@(count) forKey:kLaunch_Crash_Count];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)setupLaunchCount
{
    NSInteger count = [self safeLaunchingCount];
    count++;
    [self setupSafeCount:count];
}

- (void)recoverLaunchCount
{
    NSInteger count = [self safeLaunchingCount];
    count--;
    [self setupSafeCount:count];
}

- (void)clearLaunchCount
{
    [self setupSafeCount:0];
}

- (void)clearRootDir
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *directory = NSHomeDirectory();
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:directory error:NULL];
    for (NSString *fileName in contents) {
        NSString *removePath = [directory stringByAppendingPathComponent:fileName];
        [[NSFileManager defaultManager] removeItemAtPath:removePath error:nil];
    }
}

@end
